<template>
  <div class="container">
    <div class="content">
      <view>
        <uv-calendars mode="range" allowSameDay ref="calendars" @confirm="confirmCalendars" rangePrompt="31"/>
      </view>
      <uv-sticky bgColor="#fff">
        <view style="display: flex; ">
          <uv-tags borderColor="#FFFFFF" type="info" @click="openCalendars" text="选择日期:"
                   icon="calendar" plain></uv-tags>
          <uv-text type="info" :text="rangeData" @click="openCalendars"></uv-text>
          <uv-tags v-if="rangeData" borderColor="#FFFFFF" text="重置" plain @click="restCalendars"></uv-tags>
        </view>

        <uv-subsection :list="subsectionList" :current="current" @change="clickFn"></uv-subsection>
      </uv-sticky>

      <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback">
        <div class="list-item" v-for="(item, index) in dataList" :key="index">
          <div class="flex-box" @click="goDetail(item,1)">
            <div class="wid">
              <div class="flex">
                <uv-text :lines="2" :text="item.summary"></uv-text>
              </div>
            </div>
            <div class="">
              <uv-tags v-if="item.status === 4" :text="'已逾期'" type="warning" size="mini" plain></uv-tags>
              <uv-tags v-else-if="item.status===3" :text="'已拒绝'" type="error" size="mini" plain></uv-tags>
              <uv-tags v-else-if="item.status===2" :text="'已确认'" type="success" size="mini"
                       plain></uv-tags>
              <uv-tags v-else-if="item.status===1" :text="'待确认'" type="primary" size="mini"
                       plain></uv-tags>
            </div>
          </div>

          <div class="flex">
            <div class="text-gray">下单人：{{ item.userName }}</div>
          </div>
          <div class="flex">
            <div class="text-gray">{{ item.createTime }}</div>
            <div class="flex">
              <uv-button @tap="goAudit(item,1)" type="primary" text="确认" size="mini"
                         v-if="authority.includes('admin') && item.status === 1"></uv-button>

              <div style="width: 10px;"></div>
              <uv-button @tap="goDel(item)" type="error" text="删除" size="mini"
                         v-if="authority.includes('admin') && item.status === 1"></uv-button>

              <uv-button @tap="withdraw(item)" type="error" text="撤回" size="mini"
                         v-if="authority.includes('admin') && item.status !== 1 && item.createTimeFlag"></uv-button>

              <div style="width: 10px;"></div>
              <uv-button @tap="goDetail(item,1)" type="info" text="详情" size="mini"></uv-button>

            </div>
          </div>
        </div>
      </mescroll-body>
    </div>

    <!-- 提交确认框 -->
    <uv-modal ref="modal" title="提交确认" cancelText="拒绝" cancelColor="#f56c6c" confirmText="确认" align="center"
              content='请仔细核对物品清单后提交确认？' showCancelButton @confirm="confirm" @cancel="cancel"
              @close="close"></uv-modal>

    <uni-fab ref="fab" :pattern="{icon:'cart'}" horizontal="right" @fabClick="fabClick"/>
  </div>
</template>

<script>
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";

import CommodityAPI from '@/api/commodity'
import {dateFormat, isToday} from "@/utils/media";

export default {
  mixins: [MescrollMixin], // 使用mixin
  comments: {},
  data() {
    return {
      current: 0,
      subsectionList: [{
        name: '待确认',
        index: 0,
      }, {
        name: '已确认',
        index: 1,
      },
        {
          name: '已拒绝',
          index: 2,
        },
        {
          name: '已逾期',
          index: 3,
        }
      ],
      queryParams: {
        current: 1,
        size: 10,
        status: 1, // 1 待确认 2 已确认 3 已拒绝  4 已逾期
        startTime: '',
        endTime: ''
      },
      dataList: [],
      total: 0,
      show: false,
      form: {},
      authority: 'employee', // admin、employee、purchase、employee_manager、purchase_manager
      id: '',
      rangeData: '',
    }
  },
  onLoad(e) {
    if (e.type) {
      this.queryParams.type = e.type
    }
    this.authority = uni.getStorageSync('authInfo')?.authority

    // 默认日期范围
    const afterTime = new Date();
    this.queryParams.startTime = dateFormat(afterTime, 'yyyy-MM-dd')
    this.queryParams.endTime = dateFormat(afterTime, 'yyyy-MM-dd')
    this.rangeData = this.queryParams.startTime + ' ~ ' + this.queryParams.endTime
  },

  methods: {
    fabClick() {
      uni.navigateTo({
        url: `/subpackage/purchase/purchase`
      });
    },

    openCalendars() {
      this.$refs.calendars.open();
    },
    confirmCalendars(e) {
      let me = this;
      console.log(e)
      me.rangeData = e.range.before + ' ~ ' + e.range.after

      me.queryParams.current = 1
      me.queryParams.startTime = e.range.before
      me.queryParams.endTime = e.range.after
      me.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },
    restCalendars() {
      let me = this;
      me.rangeData = ''
      me.queryParams.current = 1
      me.queryParams.startTime = ''
      me.queryParams.endTime = ''
      me.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },
    goAudit(item) {
      this.id = item.id
      this.$refs.modal.open();
    },
    cancel() {
      this.updateStatus(this.id, 3)
    },
    close() {
    },
    confirm() {
      this.updateStatus(this.id, 2)
    },
    goDetail(item, edit) {
      let id = item.id;
      uni.navigateTo({
        url: `/subpackage/commodity/detail?id=${id}`
      })
    },
    goDel(item) {
      uni.showModal({
        content: '确认要删除吗?',
        success: (res) => {
          if (res.confirm) {
            CommodityAPI.remove(item.id)
            //(内部会自动page.num=1,再主动触发up.callback)
            this.mescroll.resetUpScroll();
          }
        }
      })
    },
    withdraw(e) {
      uni.showModal({
        content: '确认要撤回吗?',
        success: (res) => {
          if (res.confirm) {
            this.updateStatus(e.id, 1)
          }
        }
      })
    },
    updateStatus(id, status) {
      CommodityAPI.statusUpdate(id, status)
      setTimeout(() => {
        //(内部会自动page.num=1,再主动触发up.callback)
        this.mescroll.resetUpScroll();
      }, 100);

    },
    /*上拉加载的回调*/
    upCallback(page) {
      let me = this
      me.queryParams.current = page.num; // 页码, 默认从1开始
      CommodityAPI.commodityRecordList(me.queryParams).then(res => {
        let curPageData = res.data.records
        // 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
        let curPageLen = curPageData.length;
        // 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
        let totalPage = res.data.totalPage
        me.total = res.data.total
        //设置列表数据
        if (page.num === 1) this.dataList = []; //如果是第一页需手动置空列表

        curPageData.forEach(item => {
          item.createTimeFlag = isToday(item.createTime)
        })
        this.dataList = this.dataList.concat(curPageData); //追加新数据


        // 请求成功,隐藏加载状态
        //方法一(推荐): 后台接口有返回列表的总页数 totalPage
        this.mescroll.endByPage(curPageLen, totalPage);
      })
    },

    // 状态切换刷新列表
    clickFn(e) {
      this.current = e;

      let me = this;
      me.queryParams.current = 1
      me.queryParams.status = e + 1
      me.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    }
  }
}
</script>

<style scoped>
.content {
  margin: auto 0.3rem;
}

.list-item {
  width: 90%;
  margin: 0.3rem auto;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.flex-box {
  display: flex;
  justify-content: space-between;
}

.wid {
  width: 80%;
}

.flex {
  display: flex;
  justify-content: space-between;
  line-height: 1.4rem;
}

.text-gray {
  font-size: 14px;
  color: gray;
  margin: 0.2rem 0;
  width: 50%;
}
</style>